package com.xing.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.oracle.tools.packager.Log;
import com.xing.bean.WeatherResponse;
import com.xing.service.RequestUrlService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 请求url服务的实现类
 *
 * @author: xingfuhao
 * @create: 2022-03-17 00:01
 */
@Service
@Slf4j
public class RequestUrlServiceImpl implements RequestUrlService {
    //在公司里面这个url连接地址和方法名字，放在yml里面。用注解来关联起来，然后弄个实体类来绑定，调用实体
    private static final String WEATHER_URL="http://t.weather.sojson.com/api/weather/city/";

    @Autowired
    private RestTemplate restTemplate;
    //凡事带template 的一般都是模版类，增删改查等功能 封装好的

    @Override
    public WeatherResponse getWeatherResponseByCityId(String cityId) {
        //1.city 已经有了
        //2.需要 http://t.weather.sojson.com/api/weather/city/101110207
        //3.一般都是用Httpclient ,springBoot RestTemplate 类请求
        log.info("下面请求第三方");
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(WEATHER_URL + cityId, String.class);
        log.info("responseEntity --- 是"+ responseEntity);

        //获取请求的body
        String responseEntityBody = responseEntity.getBody();

        log.info("响应体是---》"+ responseEntityBody);
        //把这个 responseEntityBody 转化 WeatherResponse
        ObjectMapper objectMapper = new ObjectMapper();

        WeatherResponse weatherResponse = null;

        try {
            weatherResponse=objectMapper.readValue(responseEntityBody, WeatherResponse.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            log.info("转化出现了异常");
        }

        return weatherResponse;
    }
}
